from sqlalchemy import Column, Integer, String, Text, DateTime, BigInteger, Boolean
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
import json

Base = declarative_base()

class Share189Data(Base):
    """189云盘分享码数据模型"""
    __tablename__ = 'share_189_data'
    
    # 基础字段
    id = Column(Integer, primary_key=True, autoincrement=True, comment='主键ID')
    share_code = Column(String(50), nullable=False, unique=True, comment='分享码，作为唯一标识')
    access_code = Column(String(20), nullable=True, comment='访问码')
    
    # 状态字段
    status = Column(Integer, nullable=False, default=0, comment='状态：0-待解析，1-解析中，2-解析完成，3-解析失败，4-已导入')
    import_status = Column(Integer, nullable=False, default=0, comment='导入状态：0-待导入，1-导入中，2-导入成功，3-导入失败')
    
    # 时间字段
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    parse_start_time = Column(DateTime, nullable=True, comment='解析开始时间')
    parse_end_time = Column(DateTime, nullable=True, comment='解析结束时间')
    import_start_time = Column(DateTime, nullable=True, comment='导入开始时间')
    import_end_time = Column(DateTime, nullable=True, comment='导入结束时间')
    
    # 分享信息字段
    share_id = Column(String(100), nullable=True, comment='189云盘分享ID')
    file_id = Column(String(100), nullable=True, comment='根文件ID')
    file_name = Column(String(255), nullable=True, comment='分享文件名')
    file_size = Column(BigInteger, nullable=True, comment='文件大小（字节）')
    is_folder = Column(Boolean, nullable=True, comment='是否为文件夹')
    share_mode = Column(String(50), nullable=True, comment='分享模式')
    creator_name = Column(String(100), nullable=True, comment='分享者昵称')
    creator_id = Column(String(100), nullable=True, comment='分享者ID')
    share_date = Column(DateTime, nullable=True, comment='分享时间')
    expire_date = Column(DateTime, nullable=True, comment='失效时间')
    
    # 文件树和统计信息
    file_tree_json = Column(Text, nullable=True, comment='完整文件树JSON结构')
    total_files = Column(Integer, nullable=True, comment='总文件数量')
    total_folders = Column(Integer, nullable=True, comment='总文件夹数量')
    total_size = Column(BigInteger, nullable=True, comment='总大小（字节）')
    max_depth = Column(Integer, nullable=True, comment='最大目录深度')
    
    # 性能统计字段
    parse_duration = Column(Integer, nullable=True, comment='解析耗时（秒）')
    import_duration = Column(Integer, nullable=True, comment='导入耗时（秒）')
    imported_files = Column(Integer, nullable=True, comment='已导入文件数')
    imported_size = Column(BigInteger, nullable=True, comment='已导入大小（字节）')
    
    # 错误信息
    error_message = Column(Text, nullable=True, comment='错误信息')
    
    def __repr__(self):
        return f"<Share189Data(id={self.id}, share_code='{self.share_code}', status={self.status})>"
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'shareCode': self.share_code,
            'accessCode': self.access_code,
            'status': self.status,
            'statusText': self.get_status_text(),
            'importStatus': self.import_status,
            'importStatusText': self.get_import_status_text(),
            'createdAt': self.created_at.isoformat() if self.created_at else None,
            'updatedAt': self.updated_at.isoformat() if self.updated_at else None,
            'parseStartTime': self.parse_start_time.isoformat() if self.parse_start_time else None,
            'parseEndTime': self.parse_end_time.isoformat() if self.parse_end_time else None,
            'importStartTime': self.import_start_time.isoformat() if self.import_start_time else None,
            'importEndTime': self.import_end_time.isoformat() if self.import_end_time else None,
            'shareId': self.share_id,
            'fileId': self.file_id,
            'fileName': self.file_name,
            'fileSize': self.file_size,
            'isFolder': self.is_folder,
            'shareMode': self.share_mode,
            'creatorName': self.creator_name,
            'creatorId': self.creator_id,
            'shareDate': self.share_date.isoformat() if self.share_date else None,
            'expireDate': self.expire_date.isoformat() if self.expire_date else None,
            'fileTreeJson': json.loads(self.file_tree_json) if self.file_tree_json else None,
            'totalFiles': self.total_files,
            'totalFolders': self.total_folders,
            'totalSize': self.total_size,
            'maxDepth': self.max_depth,
            'parseDuration': self.parse_duration,
            'importDuration': self.import_duration,
            'importedFiles': self.imported_files,
            'importedSize': self.imported_size,
            'errorMessage': self.error_message
        }
    
    def get_status_text(self):
        """获取状态文本"""
        status_map = {
            0: '待解析',
            1: '解析中',
            2: '解析成功',
            3: '解析失败',
            4: '已导入'
        }
        return status_map.get(self.status, '未知状态')
    
    def get_import_status_text(self):
        """获取导入状态文本"""
        status_map = {
            0: '待导入',
            1: '导入中',
            2: '导入成功',
            3: '导入失败'
        }
        return status_map.get(self.import_status, '未知状态')
    
    def set_file_tree_json(self, data):
        """设置文件树JSON数据"""
        if data:
            self.file_tree_json = json.dumps(data, ensure_ascii=False)
    
    def get_file_tree_json(self):
        """获取文件树JSON数据"""
        if self.file_tree_json:
            try:
                return json.loads(self.file_tree_json)
            except json.JSONDecodeError:
                return None
        return None